﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WMS.Common.JWT
{
    using System.Security.Claims;

    /// <summary>
    /// ClaimsPrincipal 扩展方法
    /// </summary>
    public static class ClaimsPrincipalExtensions
    {
        /// <summary>
        /// 获取用户ID
        /// </summary>
        /// <param name="user">用户主体</param>
        /// <returns>用户ID</returns>
        public static string GetUserId(this ClaimsPrincipal user)
        {
            return user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }

        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <param name="user">用户主体</param>
        /// <returns>用户名</returns>
        public static string GetUserName(this ClaimsPrincipal user)
        {
            return user.FindFirst(ClaimTypes.Name)?.Value;
        }

        /// <summary>
        /// 获取账号
        /// </summary>
        /// <param name="user">用户主体</param>
        /// <returns>账号</returns>
        public static string GetAccount(this ClaimsPrincipal user)
        {
            return user.FindFirst("Account")?.Value;
        }

        /// <summary>
        /// 判断用户是否具有指定角色
        /// </summary>
        /// <param name="user">用户主体</param>
        /// <param name="role">角色名</param>
        /// <returns>是否具有该角色</returns>
        public static bool IsInRole(this ClaimsPrincipal user, string role)
        {
            return user.IsInRole(role);
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="user">用户主体</param>
        /// <returns>角色列表</returns>
        public static IEnumerable<string> GetRoles(this ClaimsPrincipal user)
        {
            return user.FindAll(ClaimTypes.Role).Select(c => c.Value);
        }
    }
}
